<template>
  <view class="custom-tab-bar" :style="{ paddingBottom: safeAreaBottom + 'px' }">
    <view 
      v-for="(tab, index) in tabBarStore.visibleTabs" 
      :key="tab.pagePath"
      class="tab-item"
      @tap="switchTab(index, tab.pagePath)"
    >
      <image 
        class="tab-icon" 
        :src="currentIndex === index ? tab.selectedIconPath : tab.iconPath"
        mode="aspectFit"
      />
      <text 
        class="tab-text" 
        :style="{ color: currentIndex === index ? selectedColor : color }"
      >
        {{ tab.text }}
      </text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useTabBarStore } from '@/state/tabBarConfig'

const tabBarStore = useTabBarStore()

// TabBar颜色配置（与pages.json保持一致）
const color = '#474747'
const selectedColor = '#45B05D'

// 当前选中的tab索引
const currentIndex = ref(0)

// 安全区域底部高度（适配iPhone X等有底部安全区的设备）
const safeAreaBottom = ref(0)

onMounted(() => {
  // 获取当前页面路径
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    if (currentPage && currentPage.route) {
      const route = '/' + currentPage.route
      currentIndex.value = tabBarStore.getIndexByPath(route)
      tabBarStore.setActiveIndex(currentIndex.value)
    }
  }

  // 获取系统信息，计算安全区域
  uni.getSystemInfo({
    success: (res) => {
      // 如果有安全区域信息，计算底部安全区高度
      if (res.safeAreaInsets) {
        safeAreaBottom.value = res.safeAreaInsets.bottom || 0
      } else if (res.safeArea) {
        // 兼容旧版本API
        safeAreaBottom.value = res.screenHeight - res.safeArea.bottom || 0
      }
    }
  })
})

// 切换tab
function switchTab(index: number, pagePath: string) {
  if (index === currentIndex.value) {
    return
  }
  
  currentIndex.value = index
  tabBarStore.setActiveIndex(index)
  
  // 使用uni.switchTab跳转
  uni.switchTab({
    url: pagePath,
    fail: (err) => {
      console.error('切换tab失败:', err)
      // 如果switchTab失败，尝试使用reLaunch
      uni.reLaunch({
        url: pagePath
      })
    }
  })
}
</script>

<style scoped>
.custom-tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #F2F2F2;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  border-top: 1px solid #e5e5e5;
  z-index: 9999;
  box-sizing: content-box;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
}

.tab-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 2px;
}

.tab-text {
  font-size: 10px;
  line-height: 14px;
}
</style>

